<?php

class linkerComponents extends myComponents{

	static $myOrdersLinkInfo;
	
	static $mySettingsLinkInfo;
	
	static $myCategory;
	static $myCategoryStructure;
	
	static $myProductStructure;
	static $myProductCategoriesMap = array();

	static $myNewsStructure;
	
	static $myBasketStructure;
	
	static $structureMap;

	static $myStructureActions;

        
	

        public function executeNewsItem(){
			
			// get Structure to which this NEW is linked
			if(!$this->new){
				throw new Exception('new item is not given');
			}
			// get new item group
			if(!$this->group){
				$this->group = $this->new['NewsGroup'];
			}


			// get structure new should be linked to
			if(!$this->linkStruct){
				
				if($this->group->getLinkToStruct()){
					$this->linkStruct = $this->group->getStructure();
				}else{
					return sfView::NONE;
				}
			}

			$linkStructParams = $this->fetchStructureParams($this->linkStruct);
			if((count($linkStructParams)-1) == 0)return '#';

			// default given params
			$params = $this->getVarHolder()->getAll();
			unset($params['group'], $params['linkStruct'], $params['new']);

			// specify route
			$this->route = 'newsItem_page_lvl_' . (count($linkStructParams)-1);

			// merge ALL route params
			$this->params = array_merge(
					$params,
					$linkStructParams,
					array('slug' => $this->new['slug'])
			);

        }


	public function executeIpadProduct(){
		$this->params = $this->getVarHolder()->getAll();
		$this->params['p0'] = 'est';

	}

	public function executeIpadCallSeller(){
		$this->params = $this->getVarHolder()->getAll();
		$this->params['action'] = 'activate';
		$this->params['module'] = 'ipad';
	}

	public function executeIpadGetScanned(){}

	public function executeProduct(){
			// get Structure to which this NEW is linked
			if(!$this->product){
				throw new Exception('product is not given');
			}
			// get product group
//			if(!$this->group){
//				$this->group = Doctrine::getTable('ProductGroup')->createQuery()
//									->from('ProductGroup pg')
//									->innerJoin('pg.Products p WITH p.product_id = ?', $this->product['id'])
//									->fetchOne();
//			}

			// get structure product should be linked to
			if(!$this->linkStruct){
				$productGroupKeys = array(-1);
				foreach($this->product->getProductGroups() as $group){
					$productGroupKeys[] = $group['group_id'];
				}

				
				$r = Doctrine::getTable('Structure')->createQuery('asdads')
						->from('Structure s')
						->innerJoin('s.StructureProductGroup spg')
						->whereIn('spg.group_id', $productGroupKeys)
						->andWhere('s.lang = ?', $this->getRoute()->getObject()->getLang())
						->execute();


				if($r->getFirst()){
					$this->linkStruct = $r->getFirst();
				}else{
					return '#';
				}
			}
			
			$linkStructParams = $this->fetchStructureParams($this->linkStruct);
			if((count($linkStructParams)-1) == 0)return '#';

			// default given params
			$params = $this->getVarHolder()->getAll();
			unset($params['group'], $params['linkStruct'], $params['product']);

			// specify route
			$this->route = 'product_page_lvl_' . (count($linkStructParams)-1);
			$this->full = false;
			// merge ALL route params
			$this->params = array_merge(
					$params,
					$linkStructParams,
					array('product_slug' => $this->product['slug'])
			);
		
	}

	public function executeCategory(){
		if($this->params){
			
		}

	}

	public function executeCategoryActions(){
		$this->params = $this->getVarHolder()->getAll();
	}


	public function executeProductActions(){
		$params = $this->getVarHolder()->getAll();

		if(!self::$myProductStructure){
			self::$myProductStructure = Doctrine::getTable('Structure')->findOneByParameterAndLang('productCatalog', $this->getRoute()
																													->getObject()
																													->getLang());
		}

		 $structureParams = $this->fetchStructureParams( self::$myProductStructure );


		$this->params = array_merge($structureParams,$params);
	}

	public function executeStructureActions(){

		if(!$this->node) return false;

		$params = $this->getVarHolder()->getAll();
		unset($params['node']);

		if(!self::$myStructureActions[$this->node['id']]){
			self::$myStructureActions[$this->node['id']] =
					$this->fetchStructureParams($this->node);
		}

		$this->params =
				array_merge(self::$myStructureActions[$this->node['id']],$params);
	}
	

	
	
	public function executeArticleLinkBuilder(){
		if( !isset($this->params) && isset($this->node) ){
			$this->params = $this->fetchStructureParams($this->node);
		}

		$params = $this->getVarHolder()->getAll();
		unset($params['params'], $params['node']);

		$this->params = array_merge($this->params, $params);

	}


	
	public function executeLocalizedHomepage(){
		try{
			$this->lang = isset($this->lang) ? $this->lang : $this->getRoute()->getObject()->getLang();
		}catch(Exception $e){
			$this->lang = Doctrine::getTable('Language')->findOneByAbr($this->getUser()->getCulture())->getUrl();
		}				
	}
	
	
	
	public function executeSearchLink(){
		
		$params = $this->getVarHolder()->getAll();
		
		$node = $this->getRoute()->getObject();		 
		$params['p0'] = $node['lang'];
		
		$this->params = $params;
	}
	
	
	public function executeChangeCurrency(){
		$params['currencyID'] = $this->currencyID;
		$this->params = $params;
		
	}
	
	public function executeSignIn(){
		$this->params = $this->getVarHolder()->getAll();
		
		$this->register = Doctrine::getTable('Structure')
										->findOneByParameterAndLang('register', $this->getRoute()
																						->getObject()
																						->getLang());
		$z = $this->prepareStructureNodeParams($this->register);


		$this->params = @array_merge($this->params,  $z);
		$this->params['action'] = 'signIn';
	}
	
	public function executeLogout(){
		$this->params = array();
		$this->executeSignIn();
		
		$this->params['action']='logOut';
	}
	
	public function executePasswordReminder(){
		$this->params = array();
	}
	
	public function executeRegistrationPage(){
		$params = $this->getVarHolder()->getAll();
		
		$this->mySettings = Doctrine::getTable('Structure')
										->findOneByParameterAndLang('register', $this->getRoute()
																						->getObject()
																						->getLang());
																						
			
		$z = $this->prepareStructureNodeParams($this->mySettings);
		$this->params = @array_merge($params,  $z);
	}
	
	public function executeMySettingsLinkBuilder(){
				
		if(!self::$mySettingsLinkInfo){
			$mySettings = Doctrine::getTable('Structure')
													->findOneByParameterAndLang('my settings', $this->getRoute()
																							->getObject()
																							->getLang());
				
			
			self::$mySettingsLinkInfo = $this->prepareStructureNodeParams($mySettings);
		}
		
		$this->params = array_merge( $this->getVarHolder()->getAll(), self::$mySettingsLinkInfo );
	}
	
	
	public function executeMyOrdersLinkBuilder(){
		if(!self::$myOrdersLinkInfo){
			$orders = Doctrine::getTable('Structure')
											->findOneByParameterAndLang('my settings', $this->getRoute()
																							->getObject()
																							->getLang());
	
			self::$myOrdersLinkInfo = $this->prepareStructureNodeParams($orders);
		}
		
		$this->params = array_merge( $this->getVarHolder()->getAll(), self::$myOrdersLinkInfo ); 
	}


        /*
         * PrintView for Structure or for Product
         */
	public function executePrintView(){
		if(!$this->action)
			$this->action = 'plainView';
	}
	
	public function executePlainActions(){
		$this->params = $this->getVarHolder()->getAll();
	}
	
	protected function fetchProductCategoryParams($category){
		if(!isset(self::$myProductCategoriesMap[$category['id']] )){
			$result = array();
			$this->prepareProductCategoryParams($category, $this->fetchProductCategoriesTree(), $result);
			self::$myProductCategoriesMap[$category['id']] = $result; 
		}
		
		return self::$myProductCategoriesMap[$category['id']]; 
		
	}
	
	protected function fetchProductCategoriesTree(){
		
		if(!self::$myCategory)
		 self::$myCategory = Doctrine::getTable('ProductGroup')->createQuery('fetchTree')
					->select('c.*')
					->from('ProductGroup c')
					->orderBy('c.lft asc')
					->where('c.level > ?', 0)
					->setHydrationMode(Doctrine::HYDRATE_RECORD_HIERARCHY)
					->execute();
					
		return self::$myCategory;
	}
	
	protected function fetchStructureParams( $structure ){
		if(!isset(self::$structureMap[$structure['id']]))
			self::$structureMap[$structure['id']] = $this->prepareStructureNodeParams( $structure );
		
		
		return self::$structureMap[$structure['id']]; 
	}
	
	
	// for STRUCTURE link building
	protected function prepareStructureNodeParams(Structure $node){
			foreach( $node->getNode()->getAncestors() as $anc ){
				if($anc->getLevel() > 0){
					$params['p' . ($anc->getLevel() - 1 )] = $anc->getSlug();
				}
			}
			
			$params['p' . ($node->getLevel() - 1 )] = $node->getSlug();
			return $params;
	}
	
	protected function prepareProductCategoryParams($cat, $tree, &$result){
		foreach($tree as $node){
			if($node['id'] == $cat['id']){
				$result['c' . $cat['level']] = $cat['slug'];
				return true;
			}else if(isset($node['__children'])){
				if( $this->prepareProductCategoryParams($cat, $node['__children'], $result) ){
					$result['c' . $node['level']] = $node['slug'];
					return true;
				}
			}
		}
	}
	
}